var http = require('http');
var fs = require('fs');
var url = require('url');
var libPath = require("path"); 
var mime = require("./mime").types;


// 创建服务器
http.createServer( function (request, response) {  
   // 解析请求，包括文件名
   var pathname = url.parse(request.url).pathname;
   var urlcont=url.parse(request.url).pathname;
   var flagpath=urlcont.indexOf("result")>0&&urlcont.indexOf(".png")>0?"c:\\tmpimg\\"+pathname.substr(1):pathname.substr(1);
  
   // 输出请求的文件名
   console.log("Request for " + pathname + " received.");
   
   // 从文件系统中读取请求的文件内容
   fs.readFile(flagpath, function (err, file) {
      if (err) {
         console.log(err);
         // HTTP 状态码: 404 : NOT FOUND
         // Content Type: text/plain
         response.writeHead(404, {'Content-Type': 'text/html'});
         response.end();
      }else{	 
        var contentType=""; 
        //使用路径解析模块获取文件扩展名 
        var ext=libPath.extname(pathname); 
        ext = ext ? ext.slice(1) : 'unknown';
        console.log(ext);
        var contentType = mime[ext] || "text/plain";
        response.writeHead(200, {'Content-Type': contentType});
        response.write(file, "binary");
        response.end();
      }
   });   
}).listen(8081);

// 控制台会输出以下信息
console.log('Server running at http://106.14.30.199:8081/');